import Request from '@/utils/luch/index.js';
import AuthInfo from '@/utils/auth/info.js';
import {conf} from '@/config.js'

const http = new Request();
const baseURL = conf.apiUrl;
/* 设置全局配置 */
http.setConfig((config) => { 
  config.baseURL = baseURL; //设置 api 地址
  config.header = {
    ...config.header
  }
  return config
})

/* 请求之前拦截器 */
http.interceptors.request.use((config, cancel) => {
    config.header = {
        ...config.header,
    } 
    // 默认所有请求都加上权限标识
    let token = uni.getStorageSync('token')
	if(token){
		config.header.token = token;
	}
   
    // 添加aid标识
    // config.params.aid = conf.aid;
    
    return config
})

http.interceptors.response.use(async (response) => { /* 请求之后拦截器 */
    // console.log("200 raw reponse:", response);
    if(response.data.code === 3002) {
        // uni.showToast({icon:'none',duration:2000, title: response.data.msg})
        return Promise.reject(response.data)
    }
    
    if(response.data.code !== 0) {
        uni.showToast({icon:'none',duration:2000, title: response.data.msg})
        return Promise.reject(response.data)
    }
    // console.log(response.header, typeof(response.header['WWW-Authenticate']));
    if(typeof(response.header['WWW-Authenticate']) !== 'undefined' && response.header['WWW-Authenticate'].indexOf('Bearer') > -1){
        // 无感刷新 token
        AuthInfo.setAccessToken(response.headers['WWW-Authenticate']);
        // 携带新 token 重新请求
        // let repeatRes = await http.request(response.config);
        // if ( repeatRes ) {
        //     response = repeatRes;
        // }
    }
    return response.data;

}, (response) => { // 请求错误做点什么
    console.log("err raw reponse:", response);
    if(response.statusCode == 401){
        getApp().globalData.isLogin = false;
        uni.showToast({icon:'none',duration:1500,title: "请先登录"})
        setTimeout(function(){
            uni.navigateTo({
                url: '/pages/public/login',
            })
        }, 1500)
        return Promise.reject();
    }else if(response.statusCode === 500){
        uni.showToast({ title: response.statusCode+",未知系统错误", icon: "none" })
        return Promise.reject();
    }else if(response.statusCode == 403 || response.statusCode == 405){
        uni.showToast({
            title: "您没有权限进行此项操作，请联系客服。",
            icon: "none"
        });
        return Promise.reject();
    }
    return Promise.reject();
    // return response.data;
})

export {http}